import { MessagePlugin } from 'tdesign-vue';
import { TOKEN_NAME } from '@/config/global';
import { requestAccountLogin, requestPhoneLogin, requestUserInfo, userRegesiterDto } from '@/service/login/index';

const InitUserInfo = {
  roles: [],
};

// 定义的state初始值
const state = {
  token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
  userInfo: InitUserInfo,
  routeType: 'risk',
  isRight: false,
};

const mutations = {
  // 以下是原模版，待使用
  setToken(state, token) {
    localStorage.setItem(TOKEN_NAME, token);
    state.token = token;
  },
  removeToken(state) {
    localStorage.removeItem(TOKEN_NAME);
    state.token = '';
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 修改routeType
  changeRouteType(state, val) {
    state.routeType = val;
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
  orgName: (state) => state.userInfo?.orgName,
  orgId: (state) => state.userInfo?.orgId,
  cId: (state) => state.userInfo?.id,
};

const actions = {
  register(_, userLoginDTO) {
    return new Promise((resolve) => {
      userRegesiterDto(userLoginDTO).then((res) => {
        resolve(res);
      });
    });
  },
  async loginByCount({ commit }, userLoginDTO) {
    const token = await requestAccountLogin(userLoginDTO);
    if (token) {
      MessagePlugin.success('登录成功');
      commit('setToken', token);
    }
  },
  async loginByPhone({ commit }, userLoginDTO) {
    const token = await requestPhoneLogin(userLoginDTO);
    if (token) {
      MessagePlugin.success('登录成功');
      commit('setToken', token);
    }
  },
  async getUserInfo({ commit }) {
    const res = await requestUserInfo();
    if (!res || res.isError) throw new Error('no token');
    commit('setUserInfo', {
      ...res.data,
      // hard code
      roles: ['ALL_ROUTERS'],
    });
  },
  async logout({ commit }) {
    commit('removeToken');
    commit('setUserInfo', InitUserInfo);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
